package main

import (
	"fmt"
	"log"
	"time"
	"net/http"
	"encoding/json"
	"strconv"
)

// TODO make a JSONhandler thing
func rootHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	
}

func boardsHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	j := ModelBoards()
	
	if err := json.NewEncoder(w).Encode(j); err != nil {
		panic(err)
	}
}

func threadsHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	
	if i, err := strconv.ParseInt(r.FormValue("board_id"), 10, 32); err == nil {
		j := ModelThreads(int(i))
		if err := json.NewEncoder(w).Encode(j); err != nil {
			panic(err)
		}
	}
	// TODO else fail
}

func postsHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	
	if bi, err := strconv.ParseInt(r.FormValue("board_id"), 10, 32); err == nil {
		if ti, err := strconv.ParseInt(r.FormValue("thread_id"), 10, 32); err == nil {
			j := ModelPosts(int(bi),int(ti))
			if err := json.NewEncoder(w).Encode(j); err != nil {
				panic(err)
			}
		}
		// TODO else fail
	}
	// TODO else fail
}

func main() {
	err := ModelOpen()
	if err != nil {
		return
	}
	defer ModelClose()
	
	fmt.Println("booting up server!")

	http.Handle("/", Logger(http.HandlerFunc(rootHandler), "root handler"))
	http.Handle("/boards", Logger(http.HandlerFunc(boardsHandler), "boards handler"))
	http.Handle("/threads", Logger(http.HandlerFunc(threadsHandler), "threads handler"))
	http.Handle("/posts", Logger(http.HandlerFunc(postsHandler), "posts handler"))
	
	s := &http.Server{
		Addr:           ":8080",
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Fatal(s.ListenAndServe())
}

